package cj.web.game.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.MD5Security;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.cc.controllers.BaseController;
import cj.web.cc.dao.ApplyDAO;
import cj.web.constants.MemuEnum;
import cj.web.game.dao.GameDAO;
import cj.web.sc.util.ChuCaiSmsClient;
import cj.web.uc.dao.LoginDAO;

@Path("game")
public class GameController extends BaseController{
	
	protected static final Log logger = LogFactory.getLog(GameController.class); 
	
	@Autowired
	private GameDAO gameDao;
	@Autowired
	private ApplyDAO applyDao;
	@Autowired
	private LoginDAO loginDao;
	
	@Get("homeCode")  //活动页面Code
	public String homeCode(Model model,@Param("code")String code, HttpServletResponse response) throws Exception{
		Map oauth2Reps = HttpsWenXinUtil.retOauth2Infor(code, APPID, APPSECRET);
		String access_token = oauth2Reps.get("access_token").toString();
		String openId = oauth2Reps.get("openid").toString();
		
//		String access_token = "5_t_0b1DfJd-miqaupR01BIoZkDZBL_FAVKk4TUW3_HTf9MQzfBzWD6tcJNVO0DSdSBmLDWVHckSPoQJOHq8xr9Q";
//		String openId = "ofwuNsyVHbXdpotCwZ_ZJLp7DSrQ";
		
		setCookie(response, "openId", openId);
		
		//---------------------判断是否存在绑定账号
		List<Map> reps = loginDao.getMemberByOpenId(openId);
		if(reps.size()>0 && reps.size()==1){
			//存在已经绑定过了得账号
			String memberId = reps.get(0).get("id").toString();
			String sex = reps.get(0).get("sex").toString();
			String phone = reps.get(0).get("phone").toString();
			
			setCookie(response, "phone", phone);//电话号码
			setCookie(response, "memberId", memberId);//用户ID
			setCookie(response, "sex", sex);//性别
			
			//种植的Key
			setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
			
			//Cookie中移除returnPage
			removeCookie(response, "returnPage");
			
		}else{
			model.add("currentTopMemu", MemuEnum.memulogin);
			model.add("access_token", access_token);
			model.add("openid", openId);
			//显示绑定和注册页面
			model.add("returnPage", "/game/home");
			return "/views/uc/thirdParty/bindingPhone.vm";
		}
		
		return "r:home";
	}
	
	@Get("home")  //活动页面
	public String home(Model model, HttpServletRequest request) throws Exception{
		List<Map> gamels = gameDao.queryAllForEndDate();
		for(Map rep:gamels){
			rep.put("startDate", DateUtils.getMinusTime(rep.get("startDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			rep.put("endDate", DateUtils.getMinusTime(rep.get("endDate").toString(), DateUtils.DATE_SMALL_STR, 0));
		}
		model.add("gamels", gamels);
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		
		//--------------微信签名
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		
		model.add("Title", "楚才竞赛");
		model.add("Desc", "楚才竞赛");
		model.add("LinkURL", oauth_start+gameCode+oauth_end);
		
		return "/views/apply/activityList.vm";
	}
	
	@Get("detailCode")  //活动详情Code
	public String detailCode(Model model,@Param("code")String code, @Param("state")int gameId, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,APPID,APPSECRET);
		setCookie(response, "openId", openId);
		return "r:detail?gameId=" + gameId;
	}
	
	/**
	 * 活动详情
	 * @param model
	 * @param gameId	活动ID
	 * @return
	 * @throws Exception 
	 */
	@Get("detail")
	public String detail(Model model,@Param("gameId")int gameId, HttpServletRequest request) throws Exception{
		List<Map> obj = gameDao.queryById(gameId);
		if(obj!=null && obj.size()>0){
			String endDate = obj.get(0).get("endDate").toString();
			int flagendDate = DateUtils.compareDateWithNow(DateUtils.parse(endDate));
			if(flagendDate>=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			String startDate = obj.get(0).get("startDate").toString();
			int flagstartDate = DateUtils.compareDateWithNow(DateUtils.parse(startDate));
			if(flagstartDate<=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			
			obj.get(0).put("startDate", DateUtils.getMinusTime(obj.get(0).get("startDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			obj.get(0).put("endDate", DateUtils.getMinusTime(obj.get(0).get("endDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			model.add("obj", obj.get(0));
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			String gameName = obj.get(0).get("name").toString();
			model.add("Title", gameName);
			model.add("Desc", gameName);
			model.add("LinkURL", oauth_start+gameDetailCode + gameId + oauth_end);
		}
		
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/apply/activityDetail.vm";
	}
	
	/**
	 * 验证帐号最大报名次数
	 * @param model
	 * @param gameId
	 * @param request
	 * @return
	 */
	@Post("check")
	public String check(Model model,@Param("gameId")int gameId,HttpServletRequest request,HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		String memberId = getCookieValueByName(request, "memberId");
		
		if(memberId==null || "".equals(memberId)){
			String returnPage = "/game/detail?gameId="+gameId;
			setCookie(response, "returnPage", returnPage);//活动详情
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_2);
			return "@" + jo.toString();
		}
		
		//验证活动和帐号最大报名次数
		List<Map> games = applyDao.getGameById(gameId);
		if(games != null && games.size() > 0){
			jo.put("gameType", games.get(0).get("type").toString());
			
			int maxApplyCount = Integer.parseInt(games.get(0).get("maxApplyCount").toString());//最大参赛人数
			
			List<Map> orderlis = applyDao.getOrderByUserId(Integer.parseInt(memberId), gameId);
			if(maxApplyCount<orderlis.size()){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_5);
				return "@" + jo.toString();
			}
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 给楚才查询扫码准考证号接口
	 * @param model
	 * @param code		参赛证号
	 * @param gameId	活动Id
	 * @return
	 */
	@Get("getOrInfor")
	public String getOrderInfor(Model model,@Param("code")String code,@Param("gameId")int gameId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> obj = applyDao.getOrderByCode(code,gameId);
		try {
			//status	0:没有付款；1:已付款；2:没有订单
			if(obj!=null && obj.size()>0){
			    jo.put("status",obj.get(0).get("status").toString());
			    jo.put("returnCode",obj.get(0).get("returnCode").toString());
			    jo.put("roomNo",obj.get(0).get("returnCode").toString().substring(4,6));
			    jo.put("setNo",obj.get(0).get("returnCode").toString().substring(6,9));
			}else{
				jo.put("status","2");
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 获取参赛证用户数据
	 * @param model
	 * @param code
	 * @param gameId
	 * @return
	 */
	@Get("getPermitUserInfor")
	public String getPermitUserInfor(Model model,@Param("code")String code,@Param("gameId")int gameId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> obj = applyDao.getOrderByCode(code,gameId);
		try {
			if(obj!=null && obj.size()>0){
				List<Map> gameObj = gameDao.queryById(gameId);
				jo.put("gameName",gameObj.get(0).get("name").toString());//活动名称
				jo.put("duration",obj.get(0).get("duration").toString());//活动描述
				jo.put("areaName",obj.get(0).get("areaName").toString());//考试区域
				jo.put("schoolName",obj.get(0).get("schoolName").toString());//考试学校
				jo.put("address",obj.get(0).get("address").toString());//考试地址
				jo.put("code",obj.get(0).get("code").toString());//参赛证号
				jo.put("name",obj.get(0).get("name").toString());//学生姓名
				jo.put("identityCard",obj.get(0).get("identityCard").toString());//证件号
				jo.put("area",obj.get(0).get("area").toString());//就读区域名称
				jo.put("school",obj.get(0).get("school").toString());//就读学校名称
				jo.put("grade",obj.get(0).get("grade").toString());//年级
			    jo.put("teacher",obj.get(0).get("teacher").toString());//老师
			    jo.put("parentName",obj.get(0).get("parentName").toString());//父母名称
				jo.put("parentPhone",obj.get(0).get("parentPhone").toString());//父母电话
			}else{
				jo.put("status","2");//2:没有订单
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 发送短信
	 * @param code	参赛证号
	 * @param phone	电话
	 */
	private void sendMsgByPhone(String code,String phone){
		String content = "参赛证号："+code+"，没有付款缴费，请即时支付，谢谢！";
		ChuCaiSmsClient tt = new ChuCaiSmsClient();
		String res = tt.sendSms(phone, content);
	}
	
	
}